<template>
  <div class="bg-style">
    <i-pageBody class="add_i-color">
      <div slot="page-main">
        <div class="container container-space container-space--vertical">
          <div class="container-space__child">
            <Form ref="form" :model="formdata" :label-width="100">
              <Row :gutter="20">
                <i-col style="float:left;width:400px">
                  <FormItem label="事件区域：">
                    <Row>
                      <i-col :span="12">
                        <div style="padding:0 5px">
                          <FormItem prop="city">
                            <Select
                              v-model="formdata.city"
                              placeholder="请选择市级城市"
                              style="100%"
                              @on-change="handleCity"
                              clearable
                            >
                              <Option
                                :value="value"
                                v-for="({ label, value },
                                index) in options.citys"
                                :key="index"
                                >{{ label }}</Option
                              >
                            </Select>
                          </FormItem>
                        </div>
                      </i-col>
                      <i-col :span="12">
                        <div style="padding:0 5px">
                          <FormItem prop="county">
                            <Select
                              v-model="formdata.county"
                              placeholder="请选择县级城市"
                              style="100%"
                              clearable
                            >
                              <Option
                                :value="value"
                                v-for="({ label, value },
                                index) in options.countys"
                                :key="index"
                                >{{ label }}</Option
                              >
                            </Select>
                          </FormItem>
                        </div>
                      </i-col>
                    </Row>
                  </FormItem>
                </i-col>
                <i-col style="float:left;width:250px">
                  <FormItem prop="dreventtype" label="事件类型：">
                    <Select
                      v-model="formdata.dreventtype"
                      placeholder="请选择事件类型"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.drevents"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col style="float:left;width:250px">
                  <FormItem
                    prop="controlledtype"
                    label="响应策略类型："
                    :label-width="120"
                  >
                    <Select
                      v-model="formdata.controlledtype"
                      placeholder="请选择响应策略类型"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.controlleds"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col style="float:left;width:250px">
                  <FormItem prop="time" label="响应时间：">
                    <Date-picker
                      style="width:100%"
                      type="daterange"
                      placeholder="选择响应时间"
                      v-model="formdata.time"
                      clearable
                    ></Date-picker>
                  </FormItem>
                </i-col>
                <i-col style="float:left;width:200px">
                  <Button
                    type="primary"
                    @click="handleSearch"
                    :loading="loading.search"
                  >
                    查询
                  </Button>
                  <Button
                    type="default"
                    @click="handleReset"
                    :loading="loading.reset"
                  >
                    重置
                  </Button>
                </i-col>
              </Row>
            </Form>
          </div>
          <div class="container-space__child">
            <Table
              :columns="columns"
              :data="nextData"
              border
              stripe
              :loading="tableLoading"
            ></Table>
          </div>
          <div class="container-space__child" v-show="nextData.length > 0">
            <div class="container-page">
              <PageHeader
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :page="formdata.page"
              ></PageHeader>
              <Page
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :current="formdata.page"
                @on-change="handlePage"
                show-sizer
                @on-page-size-change="handlePageSize"
              />
            </div>
          </div>
        </div>
      </div>
    </i-pageBody>
    <Modal v-model="edit.modal" width="600" title="编辑">
      <div>
        <Form
          ref="editForm"
          :model="edit.formdata"
          :rules="edit.rules"
          :label-width="160"
        >
          <FormItem label="事件编号：">
            <span>{{ edit.formdata.dreventno }}</span>
          </FormItem>
          <FormItem label="事件区域：">
            <span>{{ edit.formdata.customername }}</span>
          </FormItem>
          <FormItem prop="controlledtype" label="事件类型：">
            <Select
              v-model="edit.formdata.controlledtype"
              placeholder="请选择事件类型"
              style="100%"
              clearable
            >
              <Option
                :value="value"
                v-for="({ label, value }, index) in options.controlleds"
                :key="index"
                >{{ label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem prop="dreventtype" label="响应策略类型：">
            <Select
              v-model="edit.formdata.dreventtype"
              placeholder="请选择响应策略类型"
              style="100%"
              clearable
            >
              <Option
                :value="value"
                v-for="({ label, value }, index) in options.drevents"
                :key="index"
                >{{ label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="响应目标容量：">
            <span>{{ edit.formdata.drcap }}</span>
          </FormItem>
          <FormItem prop="starttime" label="开始时间：">
            <Date-picker
              style="width:100%"
              type="datetime"
              placeholder="选择开始时间"
              v-model="edit.formdata.starttime"
            ></Date-picker>
          </FormItem>
          <FormItem prop="endtime" label="结束时间：">
            <Date-picker
              style="width:100%"
              type="datetime"
              placeholder="选择结束时间"
              v-model="edit.formdata.endtime"
            ></Date-picker>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="edit.modal = false">
          取消
        </Button>
        <Button type="primary" @click="handleSubmit" :loading="loading.save">
          保存
        </Button>
      </div>
    </Modal>
    <Modal v-model="query.modal" width="600" title="详情">
      <div>
        <Form :label-width="160">
          <FormItem label="事件编号：">
            <span>{{ query.data.dreventno }}</span>
          </FormItem>
          <FormItem label="事件区域：">
            <span>{{ query.data.customername }}</span>
          </FormItem>
          <FormItem label="事件类型：">
            <span>{{ query.data.dreventLabel }}</span>
          </FormItem>
          <FormItem label="响应策略类型：">
            <span>{{ query.data.controlledLabel }}</span>
          </FormItem>
          <FormItem label="响应目标容量：">
            <span>{{ query.data.drcap }}</span>
          </FormItem>
          <FormItem label="开始时间：">
            <span>{{ query.data.starttime }}</span>
          </FormItem>
          <FormItem label="结束时间：">
            <span>{{ query.data.endtime }}</span>
          </FormItem>
          <FormItem label="评分：">
            <span>{{ query.data.score || "--" }}分</span>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="query.modal = false">
          关闭
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import PageHeader from "../components/page-header";
import {
  CONTROLLED_OPTIONS,
  DREVENT_OPTIONS,
  ISSUE_OPTIONS,
  REVIEW_OPTIONS,
  TABLE_COLUNMS,
  EDIT_RULES,
  CUST_RESPONSE_OPTIONS,
  ASSESS_RESULT_OPTIONS
} from "./constants";
import {
  getArea,
  getTacticsList,
  getSelectTactics,
  updateTactics,
  handleIssue
} from "@/api/scada";
import moment from "moment";
export default {
  name: "warning",
  props: {},
  data() {
    const columns = [
      ...TABLE_COLUNMS,
      {
        title: "操作",
        width: 240,
        fixed: "right",
        align: "center",
        render: (h, params) => {
          const { row } = params || {};
          const { issuecode, dreventno } = row || {};
          const buttons = [];
          // issuecode 0-有分解按钮和下发按钮 1-没有分解和下发按钮 2-无分解按钮，有下发按钮 4-有分解按钮和下发按钮
          if (["4"].includes(issuecode)) {
            buttons.push(
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small"
                  },
                  style: {
                    "margin-right": "8px"
                  },
                  nativeOn: {
                    click: () => {
                      this.handleDecompose(row);
                    }
                  }
                },
                "分解"
              )
            );
          }
          if (["0", "2"].includes(issuecode)) {
            buttons.push(
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small"
                  },
                  style: {
                    "margin-right": "8px"
                  },
                  nativeOn: {
                    click: () => {
                      this.handleIssue(row);
                    }
                  }
                },
                "下发"
              )
            );
            buttons.push(
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    "margin-right": "8px"
                  },
                  nativeOn: {
                    click: () => {
                      this.handleEdit(row);
                    }
                  }
                },
                "编辑"
              )
            );
          }

          buttons.push(
            h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                  ghost: true,
                  loading:
                    this.loading.query &&
                    this.query.data.dreventno === dreventno
                },
                nativeOn: {
                  click: () => {
                    this.handleQuery(row);
                  }
                }
              },
              "查看"
            )
          );

          return h("span", buttons);
        }
      }
    ];
    return {
      loading: {
        reset: false,
        search: false,
        normal: false,
        query: false,
        save: false
      },
      formdata: {
        city: "",
        county: "",
        dreventtype: "",
        controlledtype: "",
        time: [],
        page: 1,
        pageSize: 10,
        total: 0
      },
      options: {
        citys: [],
        countys: [],
        controlleds: CONTROLLED_OPTIONS,
        drevents: DREVENT_OPTIONS
      },
      columns,
      data: [],
      query: {
        modal: false,
        data: {
          dreventno: ""
        }
      },
      edit: {
        modal: false,
        formdata: {
          dreventno: "",
          customername: "",
          drcap: 0,
          dreventtype: null,
          controlledtype: null,
          starttime: "",
          endtime: ""
        },
        rules: EDIT_RULES
      }
    };
  },
  computed: {
    tableLoading() {
      const {
        loading: { normal, search, reset, page }
      } = this;
      return normal || search || reset || page;
    },
    nextData() {
      const { data } = this;
      return data.map((element) => {
        const {
          dreventtype,
          controlledtype,
          issuecode,
          reviewcode,
          assessResult,
          custResponse
        } = element;
        const { label: dreventLabel } =
          DREVENT_OPTIONS.find((option) => option.value === dreventtype) || {};
        const { label: controlledLabel } =
          CONTROLLED_OPTIONS.find(
            (option) => option.value === controlledtype
          ) || {};
        const { label: issueLabel } =
          ISSUE_OPTIONS.find((option) => option.value === issuecode) || {};
        const { label: reviewLabel } =
          REVIEW_OPTIONS.find((option) => option.value === reviewcode) || {};
        const { label: assessResultLabel } =
          ASSESS_RESULT_OPTIONS.find(
            (option) => option.value === assessResult
          ) || {};
        const { label: custResponseLabel } =
          CUST_RESPONSE_OPTIONS.find(
            (option) => option.value === custResponse
          ) || {};
        return {
          ...element,
          dreventLabel,
          controlledLabel,
          issueLabel,
          reviewLabel,
          assessResultLabel,
          custResponseLabel
        };
      });
    }
  },
  created() {},
  mounted() {
    this.getArea();
    this.getTacticsList();
  },
  watch: {},
  methods: {
    handleDecompose(row) {
      const { controlsId, instructId, customerid: areaNo } = row;
      this.$router.push({
        name: "emergency-decompose",
        query: { controlsId, instructId, areaNo, goback: "yes" }
      });
    },
    handleEdit(row) {
      let { starttime, endtime } = row;
      starttime = new Date(starttime);
      endtime = new Date(endtime);
      Object.assign(this.edit.formdata, { ...row, starttime, endtime });
      this.edit.modal = true;
    },
    handleQuery(row) {
      const { dreventno } = row;
      this.query.data.dreventno = dreventno;
      this.getSelectTactics(dreventno);
    },
    handleSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) return;
        this.updateTactics();
      });
    },
    handleSearch() {
      this.formdata.page = 1;
      this.getTacticsList("search");
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.formdata.page = 1;
      this.getTacticsList("reset");
    },
    handlePage(page) {
      this.formdata.page = page;
      this.getTacticsList("page");
    },
    handlePageSize(pageSize) {
      this.formdata.pageSize = pageSize;
      this.getTacticsList("page");
    },
    handleCity() {
      this.formdata.county = "";
      this.options.countys = [];
      if (this.formdata.city) {
        this.getArea("county");
      }
    },
    // 事件区域
    getArea(type = "city") {
      let pAreaNo = "";
      if (type === "city") {
        pAreaNo = "430000";
      } else if (type === "county") {
        pAreaNo = this.formdata.city;
      }
      getArea({ pAreaNo }).then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          const areas = (result || []).map((element) => {
            const { areaName, areaNo } = element;
            return {
              value: areaNo,
              label: areaName
            };
          });
          if (type === "city") {
            this.options.citys = areas;
          } else if (type === "county") {
            this.options.countys = areas;
          }
        }
      });
    },
    // 详情
    getSelectTactics(dreventno) {
      this.loading.query = true;
      getSelectTactics({ dreventno })
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const {
              dreventno,
              customername,
              drcap,
              starttime,
              endtime,
              dreventtype,
              controlledtype,
              issuecode,
              reviewcode,
              score
            } = result || {};
            const { label: dreventLabel } =
              DREVENT_OPTIONS.find((option) => option.value === dreventtype) ||
              {};
            const { label: controlledLabel } =
              CONTROLLED_OPTIONS.find(
                (option) => option.value === controlledtype
              ) || {};
            const { label: issueLabel } =
              ISSUE_OPTIONS.find((option) => option.value === issuecode) || {};
            const { label: reviewLabel } =
              REVIEW_OPTIONS.find((option) => option.value === reviewcode) ||
              {};
            const data = {
              dreventno,
              customername,
              drcap,
              starttime,
              endtime,
              dreventLabel,
              controlledLabel,
              issueLabel,
              reviewLabel,
              score
            };
            this.query.data = data;
            this.query.modal = true;
          }
        })
        .finally(() => {
          this.loading.query = false;
        });
    },
    handleIssue(row) {
      console.log(row);
      try {
        const { dreventno } = row;
        handleIssue({ dreventno })
          .then((ret) => {
            const { code } = ret;
            if (code === 200) {
              this.$Message.success("下发成功");
              this.getTacticsList();
            }
          })
          .catch((e) => {
            console.log(e);
          });
      } catch (e) {
        console.log(e);
      }
    },
    // 列表
    getTacticsList(loadingType = "normal") {
      this.loading[loadingType] = true;
      const {
        formdata: {
          city,
          county,
          dreventtype,
          controlledtype,
          time,
          page: currentPage,
          pageSize
        }
      } = this;
      const customerid = county || city || "";
      let [starttime, endtime] = time;
      starttime = starttime ? moment(starttime).format("yyyy-MM-DD") : "";
      endtime = endtime ? moment(endtime).format("yyyy-MM-DD") : "";
      const params = {
        customerid,
        dreventtype,
        controlledtype,
        starttime,
        endtime,
        currentPage,
        pageSize
      };
      getTacticsList(params)
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const { totalNum, custom } = result || {};
            this.formdata.total = totalNum || 0;
            this.data = custom || [];
          }
        })
        .finally(() => {
          this.loading[loadingType] = false;
        });
    }, // 更新事件
    updateTactics() {
      this.loading.save = true;
      const {
        edit: { formdata }
      } = this;
      let {
        dreventno,
        dreventtype,
        controlledtype,
        starttime,
        endtime,
        issuecode,
        reviewcode
      } = formdata;
      starttime = starttime
        ? moment(starttime).format("yyyy-MM-DD HH:mm:ss")
        : "";
      endtime = endtime ? moment(endtime).format("yyyy-MM-DD HH:mm:ss") : "";
      const params = {
        dreventno,
        dreventtype,
        controlledtype,
        starttime,
        endtime,
        issuecode,
        reviewcode
      };
      updateTactics(params)
        .then((ret) => {
          const { code, result } = ret;
          if (code === 200) {
            this.getTacticsList();
            this.edit.modal = false;
          }
        }).catch(e=>{
            console.log(e)
        })
        .finally(() => {
          this.loading.save = false;
        });
    }
  },
  components: { PageHeader }
};
</script>
<style scoped lang="scss">
.bg-style {
  background: url(~@/assets/img/welcome.png) center no-repeat;
  background-size: contain;
  width: 100%;
  height: 100%;
}
.container {
  padding: 20px;
  height: 100%;
  overflow: auto;
}
.container-title {
  padding-left: 10px;
  font-size: 16px;
  color: #333;
  position: relative;
}
.container-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #0893fd;
  line-height: 16px;
}

.container-space > .container-space__child:not(:last-child) {
  margin-right: 20px;
}
.container-space.container-space--vertical
  > .container-space__child:not(:last-child) {
  margin-bottom: 20px;
  margin-right: 0;
}
.container-space--inner {
  padding: 20px;
}

.container-align--center {
  text-align: center;
}
.container-align--right {
  text-align: right;
}
.container-page {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
<style>
.ivu-btn-ghost {
  color: #fff;
  background: transparent;
}
</style>
<style lang="scss" scoped>
/deep/ .ivu-table-tip table tr td {
  text-align: center;
  background-image: url("~@/assets/img/zwsj.png");
  background-position: center 60px;
  background-repeat: no-repeat;
  color: #999;
  height: 369px;
  background-size: 190px;
  span {
    display: none;
  }
}
</style>
